<template>
  <div class="staff-manage-container">
    <h1 class="page-title">🧑‍🔧 员工管理</h1>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="员工姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="职位">
          <el-select v-model="searchForm.position" placeholder="请选择" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="宠物护理师" value="caretaker"></el-option>
            <el-option label="宠物医生" value="doctor"></el-option>
            <el-option label="美容师" value="beautician"></el-option>
            <el-option label="训练师" value="trainer"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="在职" value="active"></el-option>
            <el-option label="离职" value="inactive"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增员工</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 员工列表 -->
    <el-card style="margin-top: 20px;">
      <el-table :data="staffList" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="头像" width="80">
          <template slot-scope="scope">
            <el-avatar :src="scope.row.avatar">{{ scope.row.name }}</el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="position" label="职位">
          <template slot-scope="scope">
            <el-tag :type="getPositionType(scope.row.position)">{{ scope.row.positionName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话"></el-table-column>
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip></el-table-column>
        <el-table-column prop="workYears" label="工作年限">
          <template slot-scope="scope">
            {{ scope.row.workYears }}年
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hireDate" label="入职日期" width="120"></el-table-column>
        <el-table-column label="操作" width="320" fixed="right">
          <template slot-scope="scope">
            <el-button-group>
              <el-button size="mini" type="primary" @click="handleView(scope.row)">查看</el-button>
              <el-button size="mini" type="warning" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini" type="success" @click="handleSchedule(scope.row)">排班</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog title="员工详情" :visible.sync="viewDialogVisible" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="姓名">{{ viewStaffData.name }}</el-descriptions-item>
        <el-descriptions-item label="职位">{{ viewStaffData.positionName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ viewStaffData.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ viewStaffData.email }}</el-descriptions-item>
        <el-descriptions-item label="工作年限">{{ viewStaffData.workYears }}年</el-descriptions-item>
        <el-descriptions-item label="入职日期">{{ viewStaffData.hireDate }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewStaffData.status === 'active' ? 'success' : 'info'">
            {{ viewStaffData.status === 'active' ? '在职' : '离职' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ viewStaffData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ viewStaffData.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer">
        <el-button type="primary" @click="viewDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form :model="staffForm" :rules="staffRules" ref="staffForm" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="staffForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>

        <el-form-item label="职位" prop="position">
          <el-select v-model="staffForm.position" placeholder="请选择职位" style="width: 100%">
            <el-option label="宠物护理师" value="caretaker"></el-option>
            <el-option label="宠物医生" value="doctor"></el-option>
            <el-option label="美容师" value="beautician"></el-option>
            <el-option label="训练师" value="trainer"></el-option>
            <el-option label="前台接待" value="receptionist"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="staffForm.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="staffForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>

        <el-form-item label="工作年限">
          <el-input-number v-model="staffForm.workYears" :min="0" :max="50" style="width: 100%"></el-input-number>
          <span style="margin-left: 10px">年</span>
        </el-form-item>

        <el-form-item label="入职日期" prop="hireDate">
          <el-date-picker
            v-model="staffForm.hireDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="staffForm.status">
            <el-radio label="active">在职</el-radio>
            <el-radio label="inactive">离职</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" v-model="staffForm.remark"
                    :rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 排班对话框 -->
    <el-dialog title="员工排班" :visible.sync="scheduleDialogVisible" width="700px">
      <el-calendar v-model="scheduleDate">
        <template slot="dateCell" slot-scope="{date, data}">
          <div class="schedule-cell">
            <div>{{ data.day.split('-').slice(2).join('-') }}</div>
            <div class="schedule-info" v-if="getScheduleInfo(data.day)">
              {{ getScheduleInfo(data.day) }}
            </div>
          </div>
        </template>
      </el-calendar>
      <div slot="footer">
        <el-button @click="scheduleDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import staffApi from '@/api/staff'

export default {
  name: 'StaffManage',
  data () {
    return {
      searchForm: {
        name: '',
        position: '',
        status: ''
      },
      staffList: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      viewDialogVisible: false,
      dialogTitle: '新增员工',
      scheduleDialogVisible: false,
      scheduleDate: new Date(),
      staffForm: {
        name: '',
        position: '',
        phone: '',
        email: '',
        workYears: 0,
        hireDate: '',
        status: 'active',
        remark: ''
      },
      viewStaffData: {},
      staffRules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        position: [{ required: true, message: '请选择职位', trigger: 'change' }],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        hireDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }]
      }
    }
  },
  created () {
    this.loadStaffList()
  },
  methods: {
    async loadStaffList () {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
        const res = await staffApi.getStaffList(params)
        this.staffList = res.data || []
        this.pagination.total = res.total || 0
      } catch (error) {
        this.$message.error('加载失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    handleSearch () {
      this.pagination.currentPage = 1
      this.loadStaffList()
    },
    handleReset () {
      this.searchForm = { name: '', position: '', status: '' }
      this.pagination.currentPage = 1
      this.loadStaffList()
    },
    handleAdd () {
      this.dialogTitle = '新增员工'
      this.staffForm = {
        name: '',
        position: '',
        phone: '',
        email: '',
        workYears: 0,
        hireDate: '',
        status: 'active',
        remark: ''
      }
      this.dialogVisible = true
    },
    async handleView (row) {
      try {
        const res = await staffApi.getStaffDetail(row.id)
        this.viewStaffData = res.data || {}
        this.viewDialogVisible = true
      } catch (error) {
        this.$message.error('加载详情失败：' + (error.message || '未知错误'))
      }
    },
    async handleEdit (row) {
      try {
        const res = await staffApi.getStaffDetail(row.id)
        this.dialogTitle = '编辑员工'
        this.staffForm = { ...res.data }
        this.dialogVisible = true
      } catch (error) {
        this.$message.error('加载详情失败：' + (error.message || '未知错误'))
      }
    },
    handleSchedule (row) {
      this.$message.info(`查看排班：${row.name}`)
      this.scheduleDialogVisible = true
    },
    handleDelete (row) {
      this.$confirm(`确认删除员工 "${row.name}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await staffApi.deleteStaff(row.id)
          this.$message.success('删除成功')
          this.loadStaffList()
        } catch (error) {
          this.$message.error('删除失败：' + (error.message || '未知错误'))
        }
      })
    },
    handleSubmit () {
      this.$refs.staffForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.staffForm.id) {
              await staffApi.updateStaff(this.staffForm.id, this.staffForm)
            } else {
              await staffApi.addStaff(this.staffForm)
            }
            this.$message.success('操作成功')
            this.dialogVisible = false
            this.loadStaffList()
          } catch (error) {
            this.$message.error('操作失败：' + (error.message || '未知错误'))
          }
        }
      })
    },
    getPositionType (position) {
      const typeMap = {
        'caretaker': 'primary',
        'doctor': 'success',
        'beautician': 'warning',
        'trainer': 'danger',
        'receptionist': 'info'
      }
      return typeMap[position] || 'info'
    },
    getScheduleInfo (day) {
      return null
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.loadStaffList()
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
      this.loadStaffList()
    }
  }
}
</script>

<style scoped>
.staff-manage-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.schedule-cell {
  height: 100%;
  text-align: center;
}

.schedule-info {
  font-size: 12px;
  color: #409EFF;
  margin-top: 5px;
}
</style>
